package quick.frame.core.exception;

import com.alibaba.fastjson.JSONException;
import com.elvishew.xlog.XLog;

import java.net.ConnectException;
import java.net.HttpURLConnection;

import retrofit2.HttpException;
import static quick.frame.core.exception.CodeMsg.*;

public class BaseException extends Exception{

	private static final long serialVersionUID = 1L;
	

	private CodeMsg codeMsg;
	
	public BaseException(CodeMsg cm) {
		super(cm.toString());
		this.codeMsg = cm;
	}

	public CodeMsg getcodeMsg() {
		return codeMsg;
	}

	public static BaseException handleException(Throwable e) {
		BaseException ex;
		XLog.i("tag", "e.toString = " + e.toString());
		if (e instanceof HttpException) {
			HttpException httpException = (HttpException) e;

			switch (httpException.code()) {
				case HttpURLConnection.HTTP_UNAUTHORIZED:
					ex = new BaseException(UNAUTHORIZED_ERROR);
					break;
				case HttpURLConnection.HTTP_FORBIDDEN:
					ex = new BaseException(FORBIDDEN_ERROR);
					break;
				case HttpURLConnection.HTTP_NOT_FOUND:
					ex = new BaseException(NOT_FOUND_ERROR);
					break;
				case HttpURLConnection.HTTP_CLIENT_TIMEOUT:
					ex = new BaseException(REQUEST_TIMEOUT_ERROR);
					break;
				case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
					ex = new BaseException(GATEWAY_TIMEOUT_ERROR);
					break;
				case HttpURLConnection.HTTP_INTERNAL_ERROR:
					ex = new BaseException(SERVER_ERROR);
					break;
				case HttpURLConnection.HTTP_BAD_GATEWAY:
					ex = new BaseException(BAD_GATEWAY_ERROR);
					break;
				case HttpURLConnection.HTTP_UNAVAILABLE:
					ex = new BaseException(SERVICE_UNAVAILABLE_ERROR);
					break;
				default:
					//ex.code = httpException.code();
					ex = new BaseException(INTERNET_ERROR);
					break;
			}
			return ex;
		} else if (e instanceof JSONException) {
			ex = new BaseException(JSON_ERROR);
			return ex;
		} else if (e instanceof RuntimeException) {

			return new BaseException(UNKNOWN_ERROR);
		} else if (e instanceof ConnectException) {

			return  new BaseException(CONNECTION_ERROR);
		} else if (e instanceof javax.net.ssl.SSLHandshakeException) {

			return new BaseException(CONNECTION_ERROR);
		} else {
			return new BaseException(UNKNOWN_ERROR);
		}
	}
}
